package org.szy.plugin.dev.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.szy.core.common.exception.BaseException;
import org.szy.core.common.param.CommonMoveParam;
import org.szy.core.common.param.CommonStatusParam;
import org.szy.core.common.service.impl.BaseServiceImpl;
import org.szy.core.common.uilts.TreeBuildFactory;
import org.szy.plugin.dev.entity.DevArea;
import org.szy.plugin.dev.mapper.DevAreaMapper;
import org.szy.plugin.dev.param.DevAreaQueryParam;
import org.szy.plugin.dev.pojo.DevAreaTree;
import org.szy.plugin.dev.service.DevAreaService;

import java.util.List;
import java.util.Objects;

import static org.szy.plugin.dev.entity.table.DevAreaTableDef.DEV_AREA;

/**
 * 中国行政地区表Service接口实现类
 *
 * @author wangbuhao
 * @since 2023-06-19 11:08:21
 **/
@ProxyComponent
public class DevAreaServiceImpl extends BaseServiceImpl<DevAreaMapper, DevArea> implements DevAreaService {

    @Inject
    private DevAreaMapper devAreaMapper;

    @Override
    public QueryWrapper qwByQuery(DevAreaQueryParam param) {
        QueryWrapper qw = new QueryWrapper();
        if (StrUtil.isNotEmpty(param.getColumnField())) {
            qw.select(param.getColumnField().split(","));
        }
        if (StrUtil.isNotEmpty(param.getName())) qw.and(DEV_AREA.NAME.eq(param.getName()));
        if (StrUtil.isNotEmpty(param.getCategory())) qw.and(DEV_AREA.CATEGORY.eq(param.getCategory()));
        qw.orderBy(DEV_AREA.SORT.asc());
        return qw;
    }

    @Override
    public List<DevArea> list(DevAreaQueryParam param) {
        QueryWrapper queryWrapper = qwByQuery(param);
        return this.list(queryWrapper);
    }

    @Override
    public boolean add(DevArea entity) {
        boolean exists = exists(DEV_AREA.CODE.eq(entity.getCode()));
        if (exists) throw new BaseException("区域代码已存在");
        entity.setPids(createNewPids(entity.getPid()));
        if (entity.getSort() == null) {
            long count = count();
            entity.setSort(Convert.toInt(count, 0) + 1);
        }
        String[] split = entity.getPids().split(",");
        entity.setLevel(split.length);
        return save(entity);
    }

    @Override
    public boolean edit(DevArea entity) {
        boolean exists = exists(DEV_AREA.CODE.eq(entity.getCode()).and(DEV_AREA.ID.ne(entity.getId())));
        if (exists) throw new BaseException("区域代码已存在");
        if (Objects.equals(entity.getId(), entity.getPid()))
            throw new BaseException("上级区域不能选择自己");
        entity.setPids(createNewPids(entity.getPid()));
        String[] split = entity.getPids().split(",");
        entity.setLevel(split.length);
        return updateById(entity);
    }

    @Override
    public boolean deleteById(Long id) {
        return remove(DEV_AREA.ID.eq(id).or(DEV_AREA.PIDS.like(id)));
    }

    @Override
    public List<DevAreaTree> buildTrees(List<DevArea> list) {
        List<DevAreaTree> lists = BeanUtil.copyToList(list, DevAreaTree.class);
        List<DevAreaTree> trees = new TreeBuildFactory<DevAreaTree>().doTreeBuild(lists);
        return trees;
    }

    @Override
    public boolean move(CommonMoveParam param) {
        DevArea entity = this.getById(param.getId(), "id,pid,sort");
        QueryWrapper qw = new QueryWrapper().limit(1);
        qw.select("id,pid,sort").and(DEV_AREA.PID.eq(entity.getPid()));
        List<DevArea> list;
        switch (param.getType()) {
            // 上移
            case "1":
                qw.and(DEV_AREA.SORT.lt(entity.getSort())).orderBy(DEV_AREA.SORT.desc());;
                list = list(qw);
                if (list.size() == 0) throw new BaseException("没有可交换的上级区域");
                break;
            // 下移
            case "2":
                qw.and(DEV_AREA.SORT.gt(entity.getSort())).orderBy(DEV_AREA.SORT.asc());;
                list = list(qw);
                if (list.size() == 0) throw new BaseException("没有可交换的下级区域");
                break;
            default:
                return false;
        }
        DevArea moveEntity = list.get(0);

        DevArea moveE = UpdateEntity.of(DevArea.class, entity.getId());
        moveE.setSort(moveEntity.getSort());
        devAreaMapper.update(moveE);

        DevArea moveE2 = UpdateEntity.of(DevArea.class, moveEntity.getId());
        moveE2.setSort(entity.getSort());
        devAreaMapper.update(moveE2);

        return true;
    }

    @Override
    public boolean modifyStatus(CommonStatusParam param) {
        DevArea org = new DevArea();
        org.setStatus(param.getStatus());
        QueryWrapper qw = new QueryWrapper();
        qw.and(DEV_AREA.ID.eq(param.getId()).or(DEV_AREA.PIDS.like(param.getId())));
        return devAreaMapper.updateByQuery(org, qw) > 0;
    }

    @Override
    public DevArea getByCode(String code) {
        QueryWrapper qw = new QueryWrapper();
        qw.and(DEV_AREA.CODE.eq(code));
        return getOne(qw);
    }
}
